package DataAccess;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import pojo.NhomPOJO;

public class NhomDA extends BaseDA {
	public NhomPOJO get(int id) {
		String sql = "select * from nhom where ID=" + id;
		NhomPOJO rs = null;

		try {

			ResultSet rss = provider.executeQuery(sql);
			if (rss.next()) {
				rs = getProperties(rss);
			}
		} catch (Exception e) {
			rs = null;
		}
		return rs;
	}

	public ArrayList<NhomPOJO> getNhomNguoiDung(String tenDangNhap) {
		ArrayList<NhomPOJO> rs = null;
		String sql = "select n.* from nhom n join nhom_nguoidung nnd on n.Id=nnd.IdNhom join nguoidung nd on nd.TenDangNhap=nnd.NguoiDung where nd.TenDangNhap='"
				+ tenDangNhap + "'";

		try {
			rs = new ArrayList<NhomPOJO>();
			ResultSet rss = provider.executeQuery(sql);
			while (rss.next()) {
				NhomPOJO nhom = getProperties(rss);
				rs.add(nhom);
			}
		} catch (Exception e) {
			rs = null;
		}

		return rs;
	}

	public ArrayList<NhomPOJO> getNhomNguoiDung(int idNguoiDung) {
		ArrayList<NhomPOJO> rs = null;
		String sql = "select * from nhom n join nhom_nguoidung nnd on n.id=nnd.idnhom where nnd.idnguoidung="
				+ idNguoiDung;

		try {
			rs = new ArrayList<NhomPOJO>();
			ResultSet rss = provider.executeQuery(sql);
			while (rss.next()) {
				NhomPOJO nhom = getProperties(rss);
				rs.add(nhom);
			}
		} catch (Exception e) {
			rs = null;
		}

		return rs;
	}

	public void insert(NhomPOJO nhom) {
		String spName = "spInsertNhom";
		String[] input = new String[] { nhom.getNguoiTao(), nhom.getTenNhom() };
		ResultSet rss = provider.executeStore(spName, input);
		try {
			if (rss.next()) {
				int id = rss.getInt("ID");
				nhom.setId(id);
			}
		} catch (Exception e) {
			nhom.setId(-1);
		}
	}

	@Override
	protected NhomPOJO getProperties(ResultSet rss) throws SQLException {
		NhomPOJO rs = new NhomPOJO();

		rs.setId(rss.getInt("ID"));
		rs.setTenNhom(rss.getString("TenNhom"));
		rs.setThoiGian(new Date(rss.getTimestamp("ThoiGian").getTime()));
		rs.setNguoiTao(rss.getString("NguoiTao"));
		return rs;
	}

}
